<template>
    <div class="userInfo">
        <div class="userInfo-tabs">
            <li v-for="(item,index) in tabsList" :key="index" @click="handleTabsClick(item, index)" :class="currentIndex === index ? 'active' : ''">
                {{ item.name }}
            </li>
        </div>
        <div class="userInfo-content">
            <div class="account-set" v-if="isAccount">
                <a-form-model :model="formData">
                    <a-form-model-item label="头像：">
                        <a-upload
                            action="/api/common/upload"
                            list-type="picture-card"
                            class="avatar-uploader"
                            :show-upload-list="false"
                            :before-upload="beforeUpload"
                            @change="handleUploadChange">
                            <img style="width: 100px; height: 100px;" v-if="formData.avatar" :src="`${formData.avatar}`" alt="avatar" />
                            <div v-else>
                                <a-icon :type="loading ? 'loading' : 'plus'" />
                                <div class="ant-upload-text">
                                    上传头像
                                </div>
                            </div>
                        </a-upload>
                    </a-form-model-item>
                    <div style="display: flex">
                      <a-form-model-item label="* 昵称：">
                        <a-input style="width: 290px;" v-model="formData.nickname" placeholder="请输入昵称" />
                      </a-form-model-item>
                      <a-form-model-item label="账号：" style="margin-left: 32px">
                        <a-input style="width: 290px;" disabled v-model="userInfo.username" />
                      </a-form-model-item>
                    </div>
                    <a-form-model-item label="性别：">
                        <a-select style="width: 290px;" v-model="formData.gender" placeholder="请选择性别">
                            <a-select-option value="1">男</a-select-option>
                            <a-select-option value="0">女</a-select-option>
                        </a-select>
                    </a-form-model-item>
                    <a-form-model-item label="* 真实姓名：">
                        <a-input style="width: 290px;" v-model="formData.real_name" placeholder="请输入真实姓名" />
                    </a-form-model-item>
                    <a-form-model-item label="邮箱：">
                        <a-input v-if="isEmailEdit" style="width: 290px;" v-model="formData.email" placeholder="请输入邮箱" />
                        <span v-else>{{ formData.email }}</span>
                        <a-button type="link" @click="isEmailEdit = true">修改</a-button>
                    </a-form-model-item>
                    <a-form-model-item label="微信号：">
                        <a-input v-if="isWechatEdit" style="width: 290px;" v-model="formData.wx_id" placeholder="请输入微信号" />
                        <span v-else>{{ formData.wx_id }}</span>
                        <a-button type="link" @click="isWechatEdit = true">修改</a-button>
                    </a-form-model-item>
                </a-form-model>
                <div class="form-button" @click="saveUserInfo">保存</div>
            </div>
            <div class="edit-password" v-else-if="isPassword">
                <a-form-model :model="formPass">
                    <a-form-model-item label="* 原密码：">
                        <a-input-password style="width: 290px" v-model="formPass.old_password" placeholder="" />
                    </a-form-model-item>
                    <a-form-model-item label="* 新密码：">
                        <a-input-password style="width: 290px" v-model="formPass.new_password" placeholder="6-16位密码，区分大小写" />
                    </a-form-model-item>
                    <a-form-model-item label="* 确认密码：">
                        <a-input-password style="width: 290px" v-model="formPass.confirm_password" placeholder="6-16位密码，区分大小写" />
                    </a-form-model-item>
                </a-form-model>
                <div class="form-button" @click="changePassword">提交</div>
            </div>
            <div class="edit-phone" v-else>
                <a-form :form="form" class="formclass">
                    <a-form-item>
                        <a-input v-decorator="['mobile', { rules: [{ required: true, message: '请输入手机号' }]}]" placeholder="请输入手机号"></a-input>
                    </a-form-item>
                    <a-form-item>
                        <a-input v-decorator="['captcha',{ rules: [{ required: true, message: '请输入验证码' }] },]" placeholder="请输入验证码" style="position: relative"></a-input>
                        <a-button v-if="!showSecond" type="primary" @click="getCode" style="position: absolute;right: 10px; top: -6px;background: linear-gradient(90deg, #3881F8 0%, #5EA3FE 100%); border-radius: 8px;">获取验证码</a-button>
                        <div class="count-down" v-else>{{second}}<span>s</span></div>
                    </a-form-item>
                </a-form>
                <a-button type="primary" class="form-button" @click="handleSubmit">确认修改</a-button>
            </div>
        </div>
    </div>
</template>
<script>
export default {
    props: {
        userInfo: {
            type: Object,
            default: () => {}
        }
    },
    computed: {
            imageUrl() {
                return process.env.VUE_APP_IMAGE_URL; // 自动匹配当前环境
            }
        },
    data() {
        return {
            currentIndex: 0,
            tabsList: [
                {
                    name: '账号设置',
                    type: 'account'
                },
                {
                    name: '修改密码',
                    type: 'password'
                },
                {
                    name: '修改手机号',
                    type: 'mobile'
                }
            ],
            isAccount: true,
            isPassword: false,
            formData: {
                avatar: '',
                nickname: '',
                gender: '',
                real_name: '',
                email: '',
                wx_id: ''
            },
            formPass: {
                old_password: '',
                new_password: '',
                confirm_password: ''
            },
            isEmailEdit: false,
            isWechatEdit: false,
            loading: false,
            second: 60,
            showSecond: false,
            mobile: ''
        };
    },
    beforeCreate() {
        this.form = this.$form.createForm(this, { name: 'normal_login' });
    },
    mounted() {
        this.formData.avatar = this.userInfo.avatar;
        this.formData.nickname = this.userInfo.nickname;
        this.formData.email = this.userInfo.email;
        this.formData.wx_id = this.userInfo.wx_id;
        this.formData.real_name = this.userInfo.real_name;
        this.formData.gender = String(this.userInfo.gender);
    },
    methods: {
        handleTabsClick(item, index) {
            this.currentIndex = index;
            if (item.type === 'account') {
                this.isAccount = true;
                this.isPassword = false;
            } else if (item.type === 'password') {
                this.isAccount = false;
                this.isPassword = true;
            } else {
                this.isAccount = false;
                this.isPassword = false;
            }
        },
        handleUploadChange(info) {
            // 只处理上传完成状态
            if (info.file.status === 'done') {
                console.log('文件上传完成', info.file);
                // 在这里调用业务接口
                let formData = new FormData();
                formData.append('file', info.file.originFileObj);
                this.$request.post('api/common/upload', formData).then(res => {
                    if (res.code == 1) {
                        console.log(res.data, 'res.datares.datares.data');
                        this.formData.avatar = res.data.fullurl;
                    } else {
                        this.$message.error(res.msg)
                    }
                })
            }
            // 忽略其他状态（added, uploading）
        },
        beforeUpload(file) {
            const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
            if (!isJpgOrPng) {
                this.$message.error('You can only upload JPG file!');
            }
            const isLt2M = file.size / 1024 / 1024 < 2;
            if (!isLt2M) {
                this.$message.error('Image must smaller than 2MB!');
            }
            return isJpgOrPng && isLt2M;
        },
        changePassword() {
            if (!this.formPass.old_password) {
                this.$message.error('请填写旧密码');
                return;
            }
            if (!this.formPass.new_password) {
                this.$message.error('请填写新密码');
                return;
            }
            if (this.formPass.new_password !== this.formPass.confirm_password) {
                this.$message.error('密码不一样');
                return;
            }
            this.$request.post('api/user/changepwd', this.formPass).then(res => {
                if (res.code === 1) {
                    this.$message.success('密码修改成功！')
                } else {
                    this.$message.error(res.msg)
                }
            })
        },
        saveUserInfo() {
            this.$request.post('api/user/profile', this.formData).then(res => {
                if (res.code === 1) {
                    this.$message.success('修改成功！');
                    this.$emit('getUserInfo');
                } else {
                    this.$message.error(res.msg)
                }
            })
        },
        getCode() {
            this.mobile = this.form.getFieldValue('mobile');
            if (!this.mobile) {
                this.$message.error('请输入手机号');
            } else {
                const params = {
                    mobile: this.mobile,
                    event: 'changemobile'
                }
                this.$request.post('/api/sms/send', params).then(res => {
                    if (res.code == 1) {
                        console.log(res.data);
                        this.$message.success('验证码发送成功');
                        this.second = 60;
                        this.showSecond = true;
                        this.countDown();
                    } else {
                        this.$message.error(res.msg)
                    }
                })
            }
        },
        // 倒计时
        countDown () {
            const setInnt = setInterval(() => {
                if (parseInt(this.second) > 1) {
                    this.second = this.second - 1;
                } else {
                    clearInterval(setInnt);
                    this.second = 60;
                    this.showSecond = false;
                }
            }, 1000);
        },
        handleSubmit(e) {
            e.preventDefault();
            this.form.validateFields((err, values) => {
                if (!err) {
                    this.$request.post('api/user/changemobile', values).then(res => {
                        if (res.code === 1) {
                            this.$message.success('修改成功！');
                        } else {
                            this.$message.error(res.msg)
                        }
                    })
                }
            });
        },
    }
}
</script>
<style lang="less" scoped>
.userInfo{
    width: 100%;
    text-align: left;
    .userInfo-tabs{
        display: flex;
        // margin-bottom: 20px;
        padding-bottom: 20px;
        border-bottom: 1px solid #E9E6F2;
        cursor: pointer;
        margin-bottom: 20px;
        li{
            list-style: none;
            width: 170px;
            height: 56px;
            background: #EDF5FF;
            border-radius: 8px;
            border: 1px solid #78A9FF;
            line-height: 56px;
            font-weight: 400;
            font-size: 17px;
            color: #0080FF;
            text-align: center;
            margin-right: 10px;
            &.active{
                background: linear-gradient( 90deg, #3881F8 0%, #5EA3FE 100%);
                color: #FFFFFF;
            }
        }
    }
    .form-button{
        text-align: center;
        width: 114px;
        height: 40px;
        line-height: 40px;
        background: linear-gradient( 90deg, #3881F8 0%, #5EA3FE 100%);
        border-radius: 6px;
        font-weight: 500;
        font-size: 14px;
        color: #FFFFFF;
        cursor: pointer;
    }
    .count-down{
        font-size: 16px;
        font-family: PingFang SC-Regular, PingFang SC, sans-serif;
        font-weight: 400;
        color: #FF6700;
        margin-left:21px;
        position: absolute;
        right: 10px;
        top: -6px;
    }
}
/deep/ .ant-form-item{
    display: flex;
    align-items: center;
}
/deep/ .ant-input{
  height: 54px;
  width: 300px;
}
.avatar-uploader > .ant-upload {
  width: 128px;
  height: 128px;
}
.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
</style>